package com.itheima.controller;

import com.itheima.pojo.Address;
import com.itheima.pojo.Result;
import com.itheima.Service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user/addresses")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 获取用户地址列表
     */
    @GetMapping
    public Result<List<Address>> list() {
        log.info("查询用户地址列表");
        List<Address> addressList = addressService.list();
        return Result.success(addressList);
    }

    /**
     * 获取默认地址
     */
    @GetMapping("/default")
    public Result<Address> getDefault() {
        log.info("查询用户默认地址");
        Address defaultAddress = addressService.getDefault();
        return Result.success(defaultAddress);
    }

    /**
     * 获取地址详情
     */
    @GetMapping("/{id}")
    public Result<Address> get(@PathVariable Integer id) {
        log.info("查询地址详情，ID：{}", id);
        Address address = addressService.get(id);
        return Result.success(address);
    }

    /**
     * 添加地址
     */
    @PostMapping
    public Result add(@RequestBody Address address) {
        log.info("添加新地址：{}", address);
        addressService.add(address);
        return Result.success();
    }

    /**
     * 更新地址
     */
    @PutMapping("/{id}")
    public Result update(@PathVariable Integer id, @RequestBody Address address) {
        address.setId(id); // 确保ID一致
        log.info("更新地址信息：{}", address);
        addressService.update(address);
        return Result.success();
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/{id}/default")
    public Result setDefault(@PathVariable Integer id) {
        log.info("设置默认地址，ID：{}", id);
        addressService.setDefault(id);
        return Result.success();
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除地址，ID：{}", id);
        addressService.delete(id);
        return Result.success();
    }
}